// lib/models/user.dart
import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';
//  flutter pub run build_runner build
@JsonSerializable(
  explicitToJson: true,
  includeIfNull: false,
  checked: true,
)
class User {
  @JsonKey(name: 'user_id', defaultValue: '0') // **修改：defaultValue 改为字符串 '0'**
  final String userId; // **修改：类型从 int 改为 String**

  @JsonKey(name: 'username', defaultValue: '')
  final String username;

  @JsonKey(name: 'avatar', defaultValue: '')
  final String avatar;

  @JsonKey(name: 'email', defaultValue: '')
  final String email;

  @JsonKey(name: 'phone', defaultValue: '')
  final String phone;

  @JsonKey(name: 'token', defaultValue: '')
  final String token;

  User({
    required this.userId, // 这里仍然保持 required，确保有值
    required this.username,
    this.avatar = '',
    this.email = '',
    this.phone = '',
    this.token = '',
  });

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this); // toJson 通常还是用 _$UserToJson，这里保持不变

  String get userIdValue => userId; // **修改：getter 返回 String**

  static User empty() => User(
    userId: '0', // **修改：默认值改为字符串 '0'**
    username: '',
  );

  // 如果 userId 是字符串，判断是否有效的逻辑可能需要调整为非 '0' 字符串
  bool get isValid => userId != '0' && username.isNotEmpty; // **修改：判断逻辑为非字符串 '0'**

  @override
  String toString() => 'User(userId:$userId, username:$username)';

  // 用于深拷贝
  User copyWith({
    String? userId, // **修改：copyWith 参数类型为 String?**
    String? username,
    String? avatar,
    String? email,
    String? phone,
    String? token,
  }) {
    return User(
      userId: userId ?? this.userId,
      username: username ?? this.username,
      avatar: avatar ?? this.avatar,
      email: email ?? this.email,
      phone: phone ?? this.phone,
      token: token ?? this.token,
    );
  }
}